package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.QueryObject.TravelQuery;
import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.Travel;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.respository.DestinationRespository;
import cn.wolfcode.luowowo.respository.TravelRespository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.ITravelService;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.DBHelper;
import cn.wolfcode.luowowo.util.TravelConditon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
//@Transactional  暂时不管事务
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRespository travelrRespository;

    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IDestinationService destinationService;


    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public Travel get(String id) {

        Optional<Travel> optional = travelrRespository.findById(id);
        if (optional.isPresent()) {
            Travel travel = optional.get();
            //1.维护游记对象中的 Author信息
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            //2.维护游记对象中的 目的地的信息
            travel.setDest(destinationService.get(travel.getDestId()));
            return travel;
        }
        return null;
    }

    @Override
    public List<Travel> list() {
        return travelrRespository.findAll();
    }

    @Override
    //Page对象里面包括 : 1.总页数 2.每页显示条数 3.结果集Content(Travel对象集合)
    //使用mongoTemplate 只能返回Page 需要把list封装成 page对象再返回
    public Page<Travel> query(TravelQuery qo) {

        //使用工具类
        Query query = new Query();
        //根据目的地查询
        if (StringUtils.hasLength(qo.getDestId())) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        //通过映射获取出行天数 和 人均消费的映射
        TravelConditon day = qo.getDay();
        TravelConditon perExpend = qo.getPerExpend();
        //根据出现天数 地查询
        if (day != null) {
            query.addCriteria(Criteria.where("day").lte(day.getMax()).gte(day.getMin()));
        }
        //根据人均消费地查询
        if (perExpend != null) {
            query.addCriteria(Criteria.where("perExpend").lte(perExpend.getMax()).gte(perExpend.getMin()));
        }
        //根据是否公开查询
        if (qo.getIsPublic() == 1) {
            query.addCriteria(Criteria.where("isPublic").is(Travel.ISPUBLIC_YES));
        }
        //根据是否已发布查询
        if (qo.getState() == 1) {
            query.addCriteria(Criteria.where("state").is(Travel.STATE_WAITING));
        } else if (qo.getState() == 2) {
            query.addCriteria(Criteria.where("state").is(Travel.STATE_RELEASE));
        } else if (qo.getState() == 3) {
            query.addCriteria(Criteria.where("state").is(Travel.STATE_REJECT));
        } else if (qo.getState() == 0) {
            query.addCriteria(Criteria.where("state").is(Travel.STATE_NORMAL));
        }
        //排序规则  1是根据最新排序  2是根据最热排序
        if (qo.getOrderType() == 2) {
            qo.setPageable(PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                    Sort.Direction.DESC, "createTime"));
        } else if (qo.getOrderType() == 1) {
            qo.setPageable(PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                    Sort.Direction.DESC, "viewnum"));
        }

        Page<Travel> page = DBHelper.query(mongoTemplate, Travel.class, query, qo.getPageable());

        //遍历page对象中的Content 即Travel对象的集合(结果集)
        for (Travel travel : page.getContent()) {
            UserInfo userInfo = userInfoService.get(travel.getUserId());
            //目的 维护游记中的作者字段
            travel.setAuthor(userInfo);
        }

        return page;
    }


    @Override
    public String saveOrUpdate(Travel travel) {

        //先准备 新增编辑需要的数据
        //1.目的地名字
        travel.setDestName(destinationService.get(travel.getDestId()).getName());
        //2.最后操作时间
        travel.setLastUpdateTime(new Date());

        if (!StringUtils.hasLength(travel.getId())) {
            //创建时间
            travel.setCreateTime(new Date());
            //添加
            travel.setId(null);
            travelrRespository.save(travel);
        } else {
            //条件
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(travel.getId()));
            //更新的列
            DBHelper.update(mongoTemplate, query, travel,
                    "destId", "destName", "title", "coverUrl",
                    "travelTime", "perExpend", "day", "person",
                    "isPublic", "state", "content", "summary");
        }
        return travel.getId();
    }


    @Override
    public void delete(String id) {
        travelrRespository.deleteById(id);
    }

    @Override
    public void changeState(String id, int state) {
        Optional<Travel> optional = travelrRespository.findById(id);
        if (!optional.isPresent() && state != Travel.STATE_WAITING) {
            throw new LogicException("这条数据有问题");
        }
        Travel travel = new Travel();
        travel.setLastUpdateTime(new Date());
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));

        if (state == Travel.STATE_RELEASE) {
            travel.setState(Travel.STATE_RELEASE);
            travel.setReleaseTime(new Date());
        } else {
            travel.setState(Travel.STATE_REJECT);
            travel.setReleaseTime(null);
        }
        DBHelper.update(mongoTemplate, query, travel, "lastUpdateTime", "state", "releaseTime");
    }

    @Override
    public List<Travel> getHighViewNumTravel(String destId) {
        PageRequest of = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        List<Travel> travels = travelrRespository.findByDestId(destId, of);
        return travels;
    }

    @Override
    public List<Travel> getByDestName(String destName) {
        List<Travel> travels = travelrRespository.findByDestName(destName);
        for (Travel travel : travels) {
            UserInfo userInfo = userInfoService.get(travel.getUserId());
            travel.setAuthor(userInfo);
        }
        return travels;
    }


}
